const path = require('path');
const qs = require('qs');
const request = require("sync-request");
// const moment = require("moment");
const clouddb = require('@hw-agconnect/database-server/dist/index.js')
import { AGCClient, CredentialParser } from "@agconnect/common-server"
import { user } from './db/user'

const fs = require('fs');
// 加载凭证文件
let client_name = "./db/agc-apiclient-mlc.json";
let client_path = path.join(__dirname, client_name);
let credential = CredentialParser.toCredential(client_path);
AGCClient.initialize(credential, "clientCN");

const agcClient = AGCClient.getInstance("clientCN");
clouddb.AGConnectCloudDB.initialize(agcClient);
const agconnectCloudDB = clouddb.AGConnectCloudDB.getInstance(agcClient);
//云数据库区块
const zoneName = 'mlc01';
const cloudDBZoneConfig = new clouddb.CloudDBZoneConfig(zoneName);
const mCloudDBZone = agconnectCloudDB.openCloudDBZone(cloudDBZoneConfig);

function generateRandomNumber() {
  let randomNum = Math.floor(Math.random() * 100000000000);
  return randomNum.toString().padStart(12, '0');
}

function makeSyncPostRequest(url, body) {
  try {
    // 设置请求头
    const options = {
      method: 'POST',
      headers: {
        "content-type": "application/x-www-form-urlencoded"
      },
      body: qs.stringify(body),
      // json: true // 如果body是JSON对象，设置为true会自动序列化为JSON字符串
    };

    // 发起同步POST请求
    const response = request('POST', url, options);

    // 获取响应体
    // const responseBody = response.getBody('utf8');

    // 解析JSON响应体
    const responseJson = JSON.parse(response.body);

    // 输出响应
    console.log('请求成功:', responseJson);
    return responseJson;
  } catch (error) {
    // 输出错误信息
    console.error('请求失败:', error);
    return error;
  }
}

let myHandler = async function (event, context, callback, logger) {
  const { authorizationCode } = event.body ? JSON.parse(event.body) : event
  // 请求的数据
  const postData = {
    grant_type: 'authorization_code',
    client_id: '110868193',
    client_secret: 'c9ccb38fdf17aaafcbb8bf66a5d6a604f593f17efdfe005fece495dc431f6d24',
    code: authorizationCode
  }

  const result = makeSyncPostRequest('https://oauth-login.cloud.huawei.com/oauth2/v3/token', postData);
  if (result.error) {
    let res = new context.HTTPResponse({
      code: 400,
      msg: '华为认证失败',
      data: {}
    }, {
      "faas-content-type": "json"
    }, "application/json", "200");
    callback(res);
    return;
  } else {
    const body = makeSyncPostRequest('https://account.cloud.huawei.com/rest.php?nsp_svc=GOpen.User.getInfo', {
      access_token: result.access_token,
      getNickName: 1
    });
    // 查询是否有当前用户
    const { mobileNumber: phone, displayName: name } = body
    const userCloudDBZoneQuery = clouddb.CloudDBZoneQuery.where(user).equalTo('phone', '+86-' + phone)
    const respUser = await mCloudDBZone.executeQuery(userCloudDBZoneQuery);
    const data = respUser.getSnapshotObjects()
    let userInfo = {}
    if (data.length) {
      userInfo = {
        password: data[0].password
      }
    }
    //   userInfo = {
    //     id: generateRandomNumber(),
    //     phone: '+86-' + phone,
    //     name: name || '小画家',
    //     downNum: 0,
    //     avatarUrl: '',
    //     bgWallUrl: '',
    //     sex: 3,
    //     signature: '',
    //     createTime: moment().format("YYYY/MM/DD HH:mm:ss")
    //   }
    //   const bookInfo = clouddb.CloudDBZoneGenericObject.build('user')
    //   for (const key in userInfo) {
    //     bookInfo.addFieldValue(key, userInfo[key]);
    //   }
    //   await mCloudDBZone.executeUpsert(bookInfo)
    // }
    let res = new context.HTTPResponse({
      code: 200,
      msg: '用戶信息',
      data: {
        phone,
        ...userInfo
      }
    }, {
      "faas-content-type": "json"
    }, "application/json", "200");
    callback(res);
    // request.post({
    //   url: "https://account.cloud.huawei.com/rest.php?nsp_svc=GOpen.User.getInfo",
    //   headers: {
    //     "content-type": "application/x-www-form-urlencoded"
    //   },
    //   form:
    // }, async function (error, response, body) {
    //
    // })
  }
  // request.post({
  //   url: "https://oauth-login.cloud.huawei.com/oauth2/v3/token",
  //   headers: {
  //     "content-type": "application/x-www-form-urlencoded"
  //   },
  //   form: {
  //     grant_type : 'authorization_code',
  //     client_id: '110203395',
  //     client_secret: '39f1e9fa23b85a268c2ce7a7a8a679c7631012becf0d7a22bcae62df5517e7dc',
  //     code: authorizationCode
  //   }
  // }, function (error, response, body) {
  //   body = JSON.parse(body)
  //
  // })
};

export { myHandler }
